package my.soft.aiteacher.teacher.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import my.soft.aiteacher.teacher.pojo.FileUpload;
import my.soft.aiteacher.teacher.pojo.VideoCaption;
import my.soft.aiteacher.teacher.pojo.lessonplan.Phase;
import my.soft.aiteacher.teacher.service.IFileService;
import my.soft.aiteacher.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/video")
@Tag(name = "教师-视频管理")
public class VideoController {
    @Autowired
    private IFileService fileService;
    @PreAuthorize("hasAnyAuthority('upload:videoChunk')")
    @Operation(summary = "上传视频分片")
    @PostMapping("/uploadVideo")
    public R uploadVideo(@RequestPart MultipartFile file,
                         @RequestParam Integer chunkIndex,
                         @RequestParam Long fileId,
                         @RequestParam Long userId
    ) {
        FileUpload fileUpload = fileService.uploadChunk(file, chunkIndex, fileId, userId);
        return R.success(fileUpload);
    }
    @PreAuthorize("hasAnyAuthority('query:videoId')")
    @Operation(summary = "获取视频id")
    @RequestMapping(value = "/getVideoId", method = {RequestMethod.POST})
    public R getVideoId(@RequestBody FileUpload fileUpload) {
        String fileId = fileService.uploadFile(fileUpload);
        return R.success(fileId);
    }
    @PreAuthorize("hasAnyAuthority('upload:videoCaption')")
    @Operation(summary = "上传字幕")
    @PostMapping("/uploadCaption")
    public R uploadCaption(@RequestBody List<VideoCaption> videoCaptionList) {
        String caption = fileService.uploadCaption(videoCaptionList);
        return R.success(caption);
    }
    @Operation(summary = "获取视频字幕")
    @PostMapping("/getCaption")
    public R getCaption(@RequestParam Long fileId) {
        List<VideoCaption> caption = fileService.getCaption(fileId);
        return R.success(caption);
    }

    @PreAuthorize("hasAnyAuthority('update:videoCaption')")
    @Operation(summary = "修改字幕")
    @RequestMapping(value = "/updateCaption", method = {RequestMethod.POST})
    public R updateCaption(@RequestBody List<VideoCaption> videoCaptionList) {
        List<VideoCaption> videoCaptions = fileService.updateCaption(videoCaptionList);
        return R.success("ok");
    }
    @PreAuthorize("hasAnyAuthority('query:videoInformation')")
    @Operation(summary = "教师获取个人工作台视频信息")
    @RequestMapping(value = "/getTeacherVideoInformation/{userId}", method = {RequestMethod.POST})
    public R getTeacherVideoInformation(@PathVariable Long userId) {
        List<FileUpload> teacherVideoInformation = fileService.getTeacherVideoInformation(userId);
        return R.success(teacherVideoInformation);
    }

    @Operation(summary = "删除视频")
    @PreAuthorize("hasAnyAuthority('delete:video')")
    @RequestMapping(value = "/deleteVideo/userId/{userId}/fileId/{fileId}", method = {RequestMethod.POST})
    public R deleteVideo(@PathVariable Long userId,@PathVariable Long fileId) {
        fileService.deleteVideo(userId,fileId);
        return R.success("ok");
    }
    /**
     * 流式返回视频(弃用，改用nginx)
     * @param fileId
     * @param rangeHeader
     * @return
     */
//    @Operation(summary = "流式返回视频")
//    @RequestMapping(value = "/getVideo/{fileId}", method = {RequestMethod.GET})
//    public ResponseEntity<Resource> getVideo(
//            @PathVariable String fileId,
//            @RequestHeader(value = "Range", required = false) String rangeHeader) {
//
//        try {
//            File file = fileService.getVideo(fileId);
//            Resource resource = new FileSystemResource(file);
//            long contentLength = resource.contentLength();
//
//            if (rangeHeader != null) {
//                // 解析 Range 请求（示例：bytes=0-999）
//                String[] ranges = rangeHeader.substring("bytes=".length()).split("-");
//                long rangeStart = Long.parseLong(ranges[0]);
//                long rangeEnd = ranges.length > 1 ? Long.parseLong(ranges[1]) : contentLength - 1;
//                long rangeLength = rangeEnd - rangeStart + 1;
//
//                return ResponseEntity.status(HttpStatus.PARTIAL_CONTENT)
//                        .contentType(MediaType.parseMediaType(FileUtil.getMimeType(file.toPath())))
//                        .header("Content-Range", "bytes " + rangeStart + "-" + rangeEnd + "/" + contentLength)
//                        .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(rangeLength))
//                        .body(new InputStreamResource(resource.getInputStream()));
//            }
//            return ResponseEntity.ok()
//                    .contentType(MediaType.parseMediaType(FileUtil.getMimeType(file.toPath())))
//                    .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(contentLength))
//                    .header(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=\"" + file.getName() + "\"")
//                    .body(resource);
//        } catch (Exception e) {
//            log.error("获取视频失败", e);
//            throw new RuntimeException("获取视频失败:" + e.getMessage());
//        }
//    }


}
//range头
//    public ResponseEntity<Resource> getVideo(
//            @PathVariable String fileId,
//            @RequestHeader(value = "Range", required = false) String rangeHeader) {
//
//        try {
//            File file = fileService.getVideo(fileId);
//            Resource resource = new FileSystemResource(file);
//            long contentLength = resource.contentLength();
//
//            if (rangeHeader != null) {
//                // 解析 Range 请求（示例：bytes=0-999）
//                String[] ranges = rangeHeader.substring("bytes=".length()).split("-");
//                long rangeStart = Long.parseLong(ranges[0]);
//                long rangeEnd = ranges.length > 1 ? Long.parseLong(ranges[1]) : contentLength - 1;
//                long rangeLength = rangeEnd - rangeStart + 1;
//
//                return ResponseEntity.status(HttpStatus.PARTIAL_CONTENT)
//                        .contentType(MediaType.parseMediaType(FileUtil.getMimeType(file.toPath())))
//                        .header("Content-Range", "bytes " + rangeStart + "-" + rangeEnd + "/" + contentLength)
//                        .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(rangeLength))
//                        .body(new InputStreamResource(resource.getInputStream()));
//            }
//            return ResponseEntity.ok()
//                    .contentType(MediaType.parseMediaType(FileUtil.getMimeType(file.toPath())))
//                    .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(contentLength))
//                    .header(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=\"" + file.getName() + "\"")
//                    .body(resource);
//        } catch (Exception e) {
//            log.error("获取视频失败", e);
//            throw new RuntimeException("获取视频失败:" + e.getMessage());
//        }
//    }

//}
